package com.platform.controller;

import com.alipay.easysdk.factory.Factory;
import com.platform.entity.UserOrder;
import com.platform.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.platform.common.ConfigArgs;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/aliPay")
public class AliPayController {

	@Autowired
	private ConfigArgs configArgs;

	@Resource
	private OrderService orderService;

	@PutMapping("/pay2/{id}")
	public JSONObject pay2(@PathVariable Long id) throws AlipayApiException {

		UserOrder order = orderService.getById(id);

		AlipayClient alipayClient = new DefaultAlipayClient(configArgs.getAliPayUrl(), configArgs.getAppId(),
				configArgs.getAppPrivateKey(), "json", "utf-8", configArgs.getAlipayPublicKey(), "RSA2");
		AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
		// 异步接收地址，仅支持http/https，公网可访问
		request.setNotifyUrl("");
		// 同步跳转地址，仅支持http/https
		/****** 必传参数 ******/
		JSONObject bizContent = new JSONObject();
		// 商户订单号，商家自定义，保持唯一性
		bizContent.put("out_trade_no", order.getOrderNo());
		// 支付金额，最小值0.01元
		bizContent.put("total_amount", order.getTotalPrice());
		// 订单标题，不可使用特殊符号
		bizContent.put("subject", "测试商品");
		// 电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
		bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

		/****** 可选参数 ******/
		// bizContent.put("time_expire", "2022-08-01 22:00:00");

		//// 商品明细信息，按需传入
		// JSONArray goodsDetail = new JSONArray();
		// JSONObject goods1 = new JSONObject();
		// goods1.put("goods_id", "goodsNo1");
		// goods1.put("goods_name", "子商品1");
		// goods1.put("quantity", 1);
		// goods1.put("price", 0.01);
		// goodsDetail.add(goods1);
		// bizContent.put("goods_detail", goodsDetail);

		//// 扩展信息，按需传入
		// JSONObject extendParams = new JSONObject();
		// extendParams.put("sys_service_provider_id", "2088511833207846");
		// bizContent.put("extend_params", extendParams);

		request.setBizContent(bizContent.toString());
		// AlipayTradePagePayResponse response = alipayClient.pageExecute(request,
		// "POST");
		// 如果需要返回GET请求，请使用
		AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
		String pageRedirectionData = response.getBody();
		System.out.println(pageRedirectionData);
		if (response.isSuccess()) {
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}
		JSONObject s = new JSONObject();
		s.put("data", response.getBody());
		return s;
	}

	// 沙箱无回调环境
//	@PostMapping("/notify") // 注意这里必须是POST接口
	public String payNotify(HttpServletRequest request) throws Exception {
		if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
			System.out.println("=========支付宝异步回调========");

			Map<String, String> params = new HashMap<>();
			Map<String, String[]> requestParams = request.getParameterMap();
			for (String name : requestParams.keySet()) {
				params.put(name, request.getParameter(name));
				// System.out.println(name + " = " + request.getParameter(name));
			}

			String tradeNo = params.get("out_trade_no");
			String gmtPayment = params.get("gmt_payment");
			String alipayTradeNo = params.get("trade_no");
			// 支付宝验签
			if (Factory.Payment.Common().verifyNotify(params)) {
				// 验签通过
				System.out.println("交易名称: " + params.get("subject"));
				System.out.println("交易状态: " + params.get("trade_status"));
				System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
				System.out.println("商户订单号: " + params.get("out_trade_no"));
				System.out.println("交易金额: " + params.get("total_amount"));
				System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
				System.out.println("买家付款时间: " + params.get("gmt_payment"));
				System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
				// 更新订单未已支付
				// ordersMapper.updateState(tradeNo, "已支付", gmtPayment, alipayTradeNo);
			}
		}
		return "success";
	}

}
